package mvc;

import java.util.*;
import java.sql.*;

public class News {
	
	private ArrayList<NewsPost> arr = new ArrayList();
	private int pageCount;
	private int totalpages;
	       
public News(DBconn db, int pageCount) throws SQLException
{
	NewsPost post;

	this.pageCount=pageCount;

	db.sqlQuery("SELECT count(*) FROM news").next();
	int rowcount = Integer.parseInt(db.getString("count(*)"));	

	// How many posts per side?
	int count = 4; 

	// Total pages needed
	this.totalpages = (rowcount/count);
	
	// int/int = int .. avrundningsfel
	if(rowcount % count > 0)
		this.totalpages++;

	if(this.totalpages < this.pageCount)
		this.pageCount = 1;
		

	db.sqlQuery("SELECT username,firstname,lastname,news_text,email, news_date,news_id, topic FROM person,news where person.username = news.person order by news_date desc limit "+(this.pageCount-1)*count+"," +count);

	// Put all the gb-post to show in the guestbook-model
	while(db.next()){	
		post = new NewsPost(db.getString("username"),
							db.getString("firstname"),
							db.getString("lastname"),
							db.getString("email"),
							db.getString("news_text"),
							db.getString("news_date"),
							db.getString("news_id"),
							db.getString("topic"));						
							
		this.addNewsPost(post);
	}
}
       
public void addNewsPost(NewsPost post) {
	arr.add(post);
}

public Iterator getAllNewsPosts(){
	Iterator<NewsPost> t = arr.iterator();
	return t;
	}	
	
public int getPageCount(){ return pageCount; }	

public int getTotalpages(){ return totalpages; }

public void setPagenumber(int pageCount){ 
	this.pageCount = pageCount;
}	

public void setTotalpages(int totalpages){
	this.totalpages = totalpages;
}
	
}